import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { delCartAPI, findNewCartListAPI,insertCartAPI } from '@/apis/detail'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() =>userStore.userInfo.token)
  const cartList = ref([])
  const addList = async(good) => {
    const { skuId, count } = good
    if(isLogin.value){
      await insertCartAPI({ skuId, count })
      updateNewList()
    }else{
      const item = cartList.value.find((item) =>item.skuId===good.skuId)
      if(item){
        item.count ++
      }else{
        cartList.value.push(good)
      }
    }

  }



  const singleCheck =(goods,selected) => {
    const item = cartList.value.find((item) => item.skuId===goods.skuId)
    item.selected = selected
  }

  const delList = async(skuId) => {
    if(isLogin.value){
      await delCartAPI([skuId])
      updateNewList()
    }else{
      const index = cartList.value.findIndex((item)=>item.skuId===skuId)
      cartList.value.splice(index,1)
    }
  }
  const updateNewList = async() => {
    const res =await findNewCartListAPI()
    console.log(res)
    cartList.value = res.result
  }
  const isAll =  computed(() => {
    cartList.value.every((item) => item.selected)
  })
  const changeAll = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  const checkedCount = computed(()=>cartList.value.filter((item) => item.selected).reduce((a,c)=>a+c.count,0))
  const checkedPrice = computed(()=>cartList.value.filter((item) => item.selected).reduce((a,c)=>a+c.count*c.price,0))

  const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
  const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))

  const clearCart = () => {cartList.value = []}
  return { cartList, addList,delList,allCount,allPrice,singleCheck,isAll,changeAll,checkedCount,checkedPrice,clearCart,updateNewList }
}, {
  persist: true,
})
